package service

import (
	"bluebell-backend/dao/mysql"
	"bluebell-backend/dao/redis"
	"bluebell-backend/model/po"
	"bluebell-backend/model/vo"
	"sync"
)

type PostInfo struct {
	Post *po.Post
	User *po.User
}

type CategoryAllInfo struct {
	Category *po.Category
	Post     []*po.Post
	PageInfo *PageInfo
}
type PageInfo struct {
	Category *po.Category
	PostInfo []*PostInfo
}

func AddCateGory(category *po.Category) (int, error) {
	return mysql.InsertCategory(category)
}

func DeleteCateGory(id int64) (int, error) {
	return mysql.DeleteCateGory(id)
}

func UpdateCateGoryInfo(category *po.Category) (int, error) {
	return mysql.UpdateCateGory(category)
}

func GetCategoryInfo(id int64) (*po.Category, error) {
	return mysql.GetOneCategoryByID(id)
}
func NewCategoryAllInfo() *CategoryAllInfo {
	return &CategoryAllInfo{}
}
func (f *CategoryAllInfo) GetAllPostByCategoryId(postVo *vo.PostVo) (*PageInfo, error) {

	var wg sync.WaitGroup
	wg.Add(1)
	errChan := make(chan error, 1)
	// 查询分类信息
	go func() {
		defer wg.Done()
		category, err := mysql.GetOneCategoryByID(postVo.Cid)
		if err != nil {
			errChan <- err
			return
		}
		f.Category = category
	}()
	wg.Wait()

	// 判断，如果有一个出现异常，那么程序停止
	select {
	case err := <-errChan:
		return nil, err
	default:

	}

	// 在redis中查询当前分类下的所有postId列表
	ids, err := redis.GetPostIdsWithOrder(postVo)
	if err != nil {
		return nil, err
	}

	// 批量查询
	postList, err := mysql.NewPostDaoInstance().GetPostListByIds(ids)
	if err != nil {
		return nil, err
	}
	f.Post = postList

	//// 查询该分类下所有帖子信息
	//go func() {
	//	defer wg.Done()
	//	postList, err := mysql.NewPostDaoInstance().GetPostListByCategoryId(postVo.Cid)
	//	if err != nil {
	//		errChan <- err
	//		return
	//	}
	//	f.Post = postList
	//}()

	uuids := []int64{}
	// 查询用户信息
	for _, post := range f.Post {
		uuid := post.Uid
		uuids = append(uuids, uuid)
	}
	// 批量查询
	userMap, err := mysql.MQueryUserById(uuids)
	if err != nil {
		return nil, err
	}
	postInfos := make([]*PostInfo, 0)
	for _, post := range f.Post {
		user := userMap[post.Uid]
		postInfos = append(postInfos, &PostInfo{
			Post: post,
			User: user,
		})
	}

	f.PageInfo = &PageInfo{
		Category: f.Category,
		PostInfo: postInfos,
	}
	return f.PageInfo, nil

}
